/**
 * @description 功能项管理
 * @author 李艳
 */
import {Component} from "react";
import React from "react";
import {connect} from "react-redux"
import {Input, Button, Row, Col, message, Checkbox, Modal} from "antd";
import {searchListByKeyWithTag} from "../../../commons/utils/CommonUtils";
import SimpleTable from "../../../commons/components/SimpleTable";
import {hide, show} from "../../../configs/SharedReducer";
import {
  deleteFeature,
  deleteFeatureGroup, findFeatureByFeatureGroupId, listAllFeatureGroup, saveFeature,
  saveFeatureGroup
} from "./FeatureService";
import FeatureGroupModal from "./FeatureGroupModal";
import FeatureModal from "./FeatureModal";
import HeadBreadcrumb from "../../../commons/components/breadcrumb/HeadBreadcrumb";
import DetailCard from "../../../commons/components/DetailCard";
import {rowGutter} from "../../../configs/DefaultConfig";
import FeatureItemModal from "./FeatureItemModal";
import StandardDropdown from "../../../commons/components/StandardDropdown";
import PageOperateHoc from "../../../commons/components/PageOperateHoc/index.jsx";
import CheckAuth from "../../../commons/components/CheckAuth/index.jsx";

const Search = Input.Search;
const confirm = Modal.confirm;

class FeatureView extends Component {
  constructor(props) {
    super(props);
    this.state = {
      leftSearchValue: "",
      rightSearchValue: "",
      leftData: [],
      rightData: [],
      rightSelectedRows: [],
      leftSelectedRows: [],
      rightModalVisible: false,
      leftModalVisible: false,
      confirmLoading: false,
      rightFlag: "add",
      isLeftAdd: true,
      itemParentData: null,
      itemVisible: false
    }
  }

  onLeftModalRef = (ref) => {
    this.LeftModalRef = ref;
  };
  onRightModalRef = (ref) => {
    this.RightModalRef = ref;
  };

  componentWillMount() {
    this.getLeftDataSource()
  };

  getLeftDataSource = (param) => {
    this.props.show();
    listAllFeatureGroup(param).then((result) => {
      this.setState({
        leftData: result, leftSelectedRows: [], leftSearchValue: ""
      });
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };

  getRightDataSource = (param) => {
    this.props.show();
    findFeatureByFeatureGroupId(param).then((result) => {
      this.setState({
        rightData: result, rightSelectedRows: [], rightSearchValue: ""
      });
    }).catch(err => {
    }).finally(() => {
      this.props.hide();
    });
  };


  //查找树节点
  handleLeftSearch = (value) => {
    searchListByKeyWithTag(this.state.leftData, {keyword: value}, ["code", "name"]).then(res => {
      this.setState({leftData: res, leftSearchValue: value})
    })
  };

  handleRightSearch = (value) => {
    searchListByKeyWithTag(this.state.rightData, {keyword: value}, ["code", "name"]).then(res => {
      this.setState({rightData: res, rightSearchValue: value})
    })
  };
  onAddLeftClick = () => {
    this.setState({
      leftModalVisible: true,
      isLeftAdd: true
    })
  };
  onAddRightClick = () => {
    if (!this.judgeLeftSelected()) return;
    this.setState({
      rightModalVisible: true,
      rightFlag: "add"
    })
  };
  onEditLeftClick = (record) => {
    this.setState({
      leftEditData: record,
      leftModalVisible: true,
      isLeftAdd: false
    })
  };
  onEditRightClick = (record) => {
    if (!this.judgeLeftSelected()) return;
    this.setState({
      rightEditData: record,
      rightModalVisible: true,
      rightFlag: "edit"
    })
  };
  onRightRefCreateClick = () => {
    if (!this.judgeLeftSelected()) return;
    if (!this.judgeRightSelected()) return;
    this.setState({
      rightModalVisible: true,
      rightFlag: "refAdd"
    })
  };
  //新增或编辑点击确定按钮事件
  handleLeftEdit = () => {
    //表单数据同步
    if (this.LeftModalRef && this.LeftModalRef.props.form) {
      this.LeftModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, leftModalVisible: true});
          if (this.state.isLeftAdd) {
            delete values.id
          }
          saveFeatureGroup(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求table数据刷新本地数据
              this.getLeftDataSource();
              this.setState({confirmLoading: false, leftModalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };
  //新增或编辑点击确定按钮事件
  handleRightEdit = () => {
    //表单数据同步
    if (this.RightModalRef && this.RightModalRef.props.form) {
      this.RightModalRef.props.form.validateFieldsAndScroll((err, values) => {
        if (!err) {
          //如果表单验证通过，则进行网络请求保存更改或新增的数据
          this.setState({confirmLoading: true, rightModalVisible: true});
          if (this.state.rightFlag !== "edit") {
            delete values.id
          }
          values.tenantCanUse = !!values.tenantCanUse;
          values.canMenu = !!values.canMenu;
          saveFeature(values).then((result) => {
            if (result.status === "SUCCESS") {
              message.success(result.message ? result.message : "保存成功");
              //请求table数据刷新本地数据
              let params = {featureGroupId: this.state.leftSelectedRows[0].id};
              this.getRightDataSource(params);
              this.setState({confirmLoading: false, rightModalVisible: false});
            } else {
              message.error(result.message ? result.message : "保存失败");
              this.setState({confirmLoading: false});
            }
          }).catch(err => {
            this.setState({confirmLoading: false});
          })
        }
      })
    }
  };
  handleLeftModalCancel = () => {
    this.setState({leftModalVisible: false})
  };
  handleRightModalCancel = () => {
    this.setState({rightModalVisible: false})
  };
  handleItemCancel = () => {
    this.setState({itemVisible: false})
  }
  onDeleteLeftClick = (record) => {
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deleteFeatureGroup(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据

            thiz.getLeftDataSource();
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };
  onDeleteRightClick = (record) => {
    if (!this.judgeLeftSelected()) return;
    let param = record.id;
    let thiz = this;
    confirm({
      title: "温馨提示",
      content: "删除后不可恢复，是否确定删除？",
      onOk() {
        deleteFeature(param).then((result) => {
          if (result.status === "SUCCESS") {
            message.success(result.message ? result.message : "删除成功");
            //请求table数据刷新本地数据
            let params = {featureGroupId: thiz.state.leftSelectedRows[0].id};
            thiz.getRightDataSource(params);
          } else {
            message.error(result.message ? result.message : "删除失败");
          }
        }).catch((err) => {
        }).finally(() => {
        })
      },
      onCancel() {
      },
    });
  };
  handleConfigItem = (record) => {
    this.setState({itemParentData: record, itemVisible: true});
  }

  onLeftTableSelectRow = (tableSelectRow) => {
    this.setState({leftSelectedRows: tableSelectRow, leftEditData: tableSelectRow[0] ? tableSelectRow[0] : {}});
    if (tableSelectRow[0]) {
      this.getRightDataSource({featureGroupId: tableSelectRow[0].id})
    }
  };
  onRightTableSelectRow = (tableSelectRow) => {
    this.setState({rightSelectedRows: tableSelectRow, rightEditData: tableSelectRow[0] ? tableSelectRow[0] : {}});
  };
  judgeRightSelected = () => {
    if (!this.state.rightSelectedRows[0]) {
      message.error('请选择功能项！');
      return false;
    }
    return true;
  };
  judgeLeftSelected = () => {
    if (!this.state.leftSelectedRows[0]) {
      message.error('请选择功能项组！');
      return false;
    }
    return true;
  };


  render() {
    const leftColumns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <CheckAuth
                operateCode="BASIC-HTPZ-GNXGL-EDITGROUP"
              >
                <a className={'row-operator-item'} onClick={() => this.onEditLeftClick(record)}>编辑</a>
              </CheckAuth>
              <CheckAuth
                operateCode="BASIC-HTPZ-GNXGL-DELETEGROUP"
              >
                <a className={'row-operator-item'} onClick={() => this.onDeleteLeftClick(record)}>删除</a>
              </CheckAuth>
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        width: 160
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: '所属应用模块',
        dataIndex: 'appModule.name',
        width: 240
      }
    ];
    const rightColumns = [
      {
        title: "操作",
        width: 120,
        dataIndex: "operator",
        render: (text, record, index) => {
          const button = [
            <CheckAuth
              operateCode="BASIC-HTPZ-GNXGL-CONFIG"
              key={"config"}
            >
              <a className={'row-operator-item'} onClick={() => this.handleConfigItem(record)}>配置</a>
            </CheckAuth>,
            <CheckAuth
              operateCode="BASIC-HTPZ-GNXGL-EDIT"
              key={"edit"}
            >
              <a className={'row-operator-item'} onClick={() => this.onEditRightClick(record)}>编辑</a>
            </CheckAuth>,
            <CheckAuth
              operateCode="BASIC-HTPZ-GNXGL-DELETE"
              key={"del"}
            >
              <a className={'row-operator-item'} onClick={() => this.onDeleteRightClick(record)}>删除</a>
            </CheckAuth>
          ];
          return (
            <div className={'row-operator'} onClick={(e) => {
              e.stopPropagation()
            }}>
              <StandardDropdown
                operator={button}
              />
            </div>
          )
        }
      },
      {
        title: '代码',
        dataIndex: 'code',
        sorter: true,
        width: 240
      },
      {
        title: '名称',
        dataIndex: 'name',
        width: 200
      },
      {
        title: '资源',
        dataIndex: 'url',
        width: 200
      },
      {
        title: '租户是否可用',
        dataIndex: 'tenantCanUse',
        width: 100,
        render: (text, record) => (
          <div style={{textAlign: "center"}}>
            <Checkbox checked={record.tenantCanUse === true} disabled/>
          </div>
        ),
      },
      {
        title: '是否为菜单项',
        dataIndex: 'canMenu',
        width: 100,
        render: (text, record, index) => (
          <div style={{textAlign: "center"}}>
            <Checkbox checked={record.canMenu === true} disabled/>
          </div>
        ),
      },
      {
        title: '功能项类型',
        dataIndex: 'featureType',
        width: 100,
        render:(text)=>{
           if(text==="page"){
             return "页面";
           }else {
             return "操作";
           }
        }

      },
    ];
    const leftTitle = () => {
      return [
        <CheckAuth
          operateCode="BASIC-HTPZ-GNXGL-ADDGROUP"
          key="addRuleLeft"
        >
          <Button className={"primaryButton"} type={"primary"}
                  onClick={this.onAddLeftClick}>新增</Button>
        </CheckAuth>
      ]
    };

    //表头搜索框
    const leftSearch = () => {
      return [
        <Search
          key="leftSearch"
          placeholder="输入名称或代码进行查询"
          onSearch={value => this.handleLeftSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    const rightTitle = () => {
      return [
        <CheckAuth
          operateCode="BASIC-HTPZ-GNXGL-ADD"
          key="addRule"
        >
          <Button className={"primaryButton"} type={"primary"}
                  onClick={this.onAddRightClick}>新增</Button>
        </CheckAuth>,
        <CheckAuth
          operateCode="BASIC-HTPZ-GNXGL-REF"
          key="rightRef"
        >
          <Button
            onClick={this.onRightRefCreateClick}>参考创建</Button>
        </CheckAuth>,
      ]
    };

    //表头搜索框
    const rightSearch = () => {
      return [
        <Search
          key="search"
          placeholder="输入名称或代码进行查询"
          onSearch={value => this.handleRightSearch(value)}
          style={{width: 220}}
          allowClear
        />
      ]
    };
    const {itemVisible, itemParentData} = this.state;
    return (
      <HeadBreadcrumb
        //pathData={[{name:"功能项管理"}]}
        className={"allocation-page"}
        style={{overflow: "hidden"}}
      >
        <Row gutter={rowGutter} style={{height: "100%", display: this.state.isPositionConfig ? "none" : "block"}}>
          {/*左边的树状控件*/}
          <Col span={10} style={{height: "100%"}}>
            <DetailCard
              title="功能项组"
              style={{height: "100%"}}
            >
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{leftTitle()}</div>
                <div className={'tbar-search-box'}>{leftSearch()}</div>
              </div>
              <SimpleTable
                data={this.state.leftSearchValue ? this.state.leftData.filter(item => item.tag === true) : this.state.leftData}
                columns={leftColumns}
                onSelectRow={this.onLeftTableSelectRow}
                rowsSelected={this.state.leftSelectedRows}
              />
              <FeatureGroupModal
                modalVisible={this.state.leftModalVisible}
                confirmLoading={this.state.confirmLoading}
                handleOk={this.handleLeftEdit}
                handleCancel={this.handleLeftModalCancel}
                onRef={this.onLeftModalRef}
                defaultValue={this.state.leftEditData ? this.state.leftEditData : {}}
                isAdd={this.state.isLeftAdd}
              />
            </DetailCard>
          </Col>
          {/*右边的表格控件*/}
          <Col span={14} style={{height: "100%"}}>
            <DetailCard
              title="功能项(页面级)"
              className={"child-card"}
              style={{height: "100%"}}
            >
              <div className={'tbar-box'}>
                <div className={'tbar-btn-box'}>{rightTitle()}</div>
                <div className={'tbar-search-box'}>{rightSearch()}</div>
              </div>
              <SimpleTable
                data={this.state.rightSearchValue ? this.state.rightData.filter(item => item.tag === true) : this.state.rightData}
                columns={rightColumns}
                onSelectRow={this.onRightTableSelectRow}
                rowsSelected={this.state.rightSelectedRows}
              />

              {
                itemVisible ? <FeatureItemModal
                  visible={itemVisible}
                  parentData={itemParentData}
                  onCancel={this.handleItemCancel}
                /> : null
              }
              <FeatureModal
                modalVisible={this.state.rightModalVisible}
                confirmLoading={this.state.confirmLoading}
                handleOk={this.handleRightEdit}
                handleCancel={this.handleRightModalCancel}
                onRef={this.onRightModalRef}
                defaultValue={this.state.rightEditData ? this.state.rightEditData : {}}
                featureGroupId={this.state.leftSelectedRows[0] ? this.state.leftSelectedRows[0].id : ""}
                rightFlag={this.state.rightFlag}
              />
            </DetailCard>
          </Col>
        </Row>
      </HeadBreadcrumb>
    )
  }
}

const mapStateToProps = (state) => {
  return {};
};

const mapDispatchToProps = (dispatch) => {
  return {
    show: () => {
      dispatch(show())
    },
    hide: () => {
      dispatch(hide())
    },
  }
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(PageOperateHoc(FeatureView))
